import type { Article, QueryArticlesParams, ArticlesResponse } from '~/types'

export const useArticles = () => {
  const { $api } = useNuxtApp()

  // 获取文章列表
  const getArticles = async (params?: QueryArticlesParams): Promise<ArticlesResponse> => {
    const response = await $api('/articles', {
      params,
    })
    return response as ArticlesResponse
  }

  // 获取单篇文章
  const getArticle = async (idOrSlug: number | string): Promise<Article> => {
    const response = await $api(`/articles/${idOrSlug}`)
    return response as Article
  }

  // 创建文章
  const createArticle = async (data: Partial<Article>): Promise<Article> => {
    const response = await $api('/articles', {
      method: 'POST',
      body: data,
    })
    return response as Article
  }

  // 更新文章
  const updateArticle = async (id: number, data: Partial<Article>): Promise<Article> => {
    const response = await $api(`/articles/${id}`, {
      method: 'PATCH',
      body: data,
    })
    return response as Article
  }

  // 删除文章
  const deleteArticle = async (id: number): Promise<void> => {
    await $api(`/articles/${id}`, {
      method: 'DELETE',
    })
  }

  // 点赞文章
  const likeArticle = async (id: number): Promise<void> => {
    await $api(`/articles/${id}/like`, {
      method: 'POST',
    })
  }

  // 获取精选文章
  const getFeaturedArticles = async (limit = 5): Promise<Article[]> => {
    const response = await $api('/articles/featured', {
      params: { limit },
    })
    return response as Article[]
  }

  // 获取相关文章
  const getRelatedArticles = async (id: number, limit = 5): Promise<Article[]> => {
    const response = await $api(`/articles/${id}/related`, {
      params: { limit },
    })
    return response as Article[]
  }

  // 获取分类列表
  const getCategories = async (): Promise<{ category: string; count: number }[]> => {
    const response = await $api('/articles/categories')
    return response as { category: string; count: number }[]
  }

  // 获取标签列表
  const getTags = async (): Promise<{ tag: string; count: number }[]> => {
    const response = await $api('/articles/tags')
    return response as { tag: string; count: number }[]
  }

  return {
    getArticles,
    getArticle,
    createArticle,
    updateArticle,
    deleteArticle,
    likeArticle,
    getFeaturedArticles,
    getRelatedArticles,
    getCategories,
    getTags,
  }
}

